/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.openness.crawler.frontier;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.hadoop.hbase.util.Bytes;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.openness.crawler.crawler.Configurable;
import com.openness.crawler.crawler.CrawlConfig;
import com.openness.crawler.hbase.HBaseUtil;
import com.openness.crawler.lock.DistributedLock;
import com.openness.crawler.util.Constants;

public class Counters extends Configurable {

	public class ReservedCounterNames {

		public final static String SCHEDULED_PAGES = "scheduledpages";

		public final static String PROCESSED_PAGES = "processedpages";

	}

	private static final Logger LOGGER = LoggerFactory
			.getLogger(Counters.class);

	private ZooKeeper zk;

	private DistributedLock lock;

	public Counters(ZooKeeper zk, CrawlConfig config) throws IOException {
		super(config);

		LOGGER.info("Counters initialize");

		this.zk = zk;

		this.lock = new DistributedLock(zk, Constants.ZK_LOCK_COUNTERS,
				Constants.ZK_LOCK_PREFIX);

		if (config.isResumableCrawling()) {
			Map<String, byte[]> result = HBaseUtil.getRow(
					Constants.HBASE_TABLE_COUNTERS,
					Constants.HBASE_TABLE_COUNTERS_ROWKEY);

			if (result != null && result.size() > 0) {
				for (Entry<String, byte[]> entry : result.entrySet()) {
					try {
						zk.setData(Constants.ZK_COUNTERS_DIR
								+ Constants.ZK_SEPARATOR + entry.getKey(),
								entry.getValue(), -1);
					} catch (Exception e) {
						throw new IOException(
								"Counters constructor create counter error: "
										+ e.toString());
					}
				}
			}
		}

		LOGGER.info("Counters initialize success");
	}

	public long getValue(String name) {
		lock.lock();

		try {
			byte[] data = zk.getData(Constants.ZK_COUNTERS_DIR
					+ Constants.ZK_SEPARATOR + name, false, null);

			if (data != null && data.length > 0) {
				return Bytes.toLong(data);
			}
		} catch (Exception e) {
			LOGGER.error("Counters getValue error: " + e.toString());
		} finally {
			lock.unlock();
		}

		return 0;
	}

	private void setValue(String name, long value) {
		try {
			HBaseUtil.putRow(Constants.HBASE_TABLE_COUNTERS,
					Constants.HBASE_TABLE_COUNTERS_ROWKEY, name,
					Bytes.toBytes(value));

			String path = Constants.ZK_COUNTERS_DIR + Constants.ZK_SEPARATOR
					+ name;

			zk.setData(path, Bytes.toBytes(value), -1);
		} catch (Exception e) {
			LOGGER.error("Counters setValue error: " + e.toString());
		}
	}

	public void increment(String name) {
		increment(name, 1);
	}

	public void increment(String name, long addition) {
		lock.lock();

		try {
			long prevValue = getValue(name);

			setValue(name, prevValue + addition);
		} catch (Exception e) {
			LOGGER.error("Counters increment error: " + e.toString());
		} finally {
			lock.unlock();
		}
	}

	public void sync() {

	}

	public void close() {

	}

}
